package cn.demoncat.util.web.filter;

import cn.demoncat.util.web.constant.MimeConstant;
import cn.demoncat.util.web.entity.RepeatableServletRequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Json请求过滤器
 *
 * 1、继承 OncePerRequestFilter，一个请求只过滤一次
 *
 * 2、如果是 Json 请求，替换为 RepeatableServletRequestWrapper，以便重复读取请求体
 *
 * @author 延晓磊
 * @since 2023年02月08日
 */
@Component
public class JsonRequestFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (!(request instanceof RepeatableServletRequestWrapper) && StringUtils.startsWith(request.getContentType(), MimeConstant.JSON)) {
            // 非自定义Request + 为JSON请求 = 替换为可重复读的RequestWrapper
            request = new RepeatableServletRequestWrapper(request);
        }
        chain.doFilter(request, response);
    }

}
